package com.ssh.nio.channel;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

import com.mongodb.util.ThreadUtil;

/**
 * socket的创建方式举例
 * 
 * @author Administrator
 * 
 */
public class SocketChannelTest {

	public static void main(String[] args) throws IOException,
			InterruptedException {
		socketChannelopen();

		// serverSocketBindTest();
	}

	private static void serverSocketBindTest() throws IOException {
		ServerSocketChannel sschannel = ServerSocketChannel.open();
		ServerSocket ssocket = sschannel.socket();
		ssocket.bind(new InetSocketAddress(1111));
		// 立即结束
		sschannel.configureBlocking(false);
		// 阻塞
		// sschannel.configureBlocking(true);

		sschannel.accept();

		System.out.println("created...");
	}

	private static void socketChannelopen() throws IOException {
		InetSocketAddress inet = new InetSocketAddress("127.0.0.1", 1234);
		// 不能用@link #java.net.Socket 的getChannel（）方法 否则返回null
		SocketChannel channel = SocketChannel.open();
		// 设置为非阻塞模式
		// channel.;
		channel.configureBlocking(false);

		channel.connect(inet);

		while (!channel.finishConnect()) {
			ThreadUtil.sleep(1000);
			System.out.println(channel.isConnected());
			ByteBuffer bf = ByteBuffer.allocate(1024 * 16);
			// OutputStream out=new
			bf.clear();
			channel.read(bf);
			bf.flip();
			while (bf.hasRemaining()) {
				System.out.println(bf.getChar());
			}
			if (!channel.isBlocking()) {
				System.out.println("-----no block---");
			}
		}
		channel.close();

	}
}
